<template>
	<view class="diy-product" :style="{ background: itemData.style.background }">
		<view :class="['display__' + itemData.style.display]">
			<template v-if="itemData.style.display == 'list'">
				<!-- 纵向列表使用scroll-view包裹，便于监听滚动 -->
				<scroll-view class="vertical-scroll" scroll-y="true" @scroll="handleVerticalScroll"
					:scroll-with-animation="false">
					<view class="product-list" :class="['column__' + itemData.style.column]">
						<view class="product-item" v-for="(product, index) in itemData.data" :key="index"
							@click="gotoDetail(product.product_id)">
							<!-- 单列商品 -->
							<template v-if="itemData.style.column == 1">
								<view class="product-item-box">
									<view class="product-cover">
										<image :src="product.showImage ? product.image : placeholderImg"
											mode="aspectFit" class="product-img" :data-index="index" :lazy-load="false">
										</image>
									</view>
									<view class="product-info">
										<view v-if="itemData.style.show.productName" class="product-title">
											<text>{{ product.product_name }}</text>
										</view>
										<view v-if="itemData.style.show.sellingPoint" class="selling-point gray9">
											<text>{{ product.selling_point }}</text>
										</view>
										<view v-if="itemData.style.show.productSales" class="already-sale">
											<text>已售{{ product.product_sales }}件</text>
										</view>
										<view class="price d-s-c mt10">
											<view v-if="itemData.style.show.productPrice" class="theme-price">
												<text>¥</text>
												<text>{{ product.product_price }}</text>
											</view>
											<view class="ml10 gray9 text-d-line f28"
												v-if="itemData.style.show.linePrice && product.line_price > 0">
												<text>¥</text>
												<text>{{ product.line_price }}</text>
											</view>
										</view>
									</view>
								</view>
							</template>

							<!-- 两列/三列商品 -->
							<template v-else>
								<view class="product-cover">
									<image :src="product.showImage ? product.image : placeholderImg" mode="aspectFill"
										class="product-img" :data-index="index" :lazy-load="false">
									</image>
								</view>
								<view class="product-info">
									<view v-if="itemData.style.show.productName == 1" class="product-title">
										{{ product.product_name }}
									</view>
									<view class="price d-s-c">
										<view v-if="itemData.style.show.productPrice == 1" class="theme-price">
											<text class="f22">¥</text>
											<text>{{ product.product_price }}</text>
										</view>
										<view class="ml20 gray9 text-d-line"
											v-if="itemData.style.show.linePrice == 1 && product.line_price > 0">
											<text class="f22">¥</text>{{ product.line_price }}
										</view>
									</view>
								</view>
							</template>
						</view>
					</view>
				</scroll-view>
			</template>
			<template v-else>
				<scroll-view :scroll-top="scrollTop" scroll-x="true" class="horizontal-scroll"
					@scroll="handleHorizontalScroll">
					<view class="product-list" :class="['column__' + itemData.style.column]">
						<view v-for="(product, index) in itemData.data" :key="index"
							@click="gotoDetail(product.product_id)">
							<view class="product-item">
								<view class="product-cover">
									<image :src="product.showImage ? product.image : placeholderImg" mode="aspectFill"
										class="product-img" :data-index="index" :lazy-load="false">
									</image>
								</view>
								<view class="product-info">
									<view v-if="itemData.style.show.productName == 1" class="product-title">
										{{ product.product_name }}
									</view>
									<view class="price d-s-c f12">
										<view v-if="itemData.style.show.productPrice == 1" class="theme-price">
											<text>¥</text>
											<text>{{ product.product_price }}</text>
										</view>
										<view class="ml10 gray9 text-d-line"
											v-if="itemData.style.show.linePrice == 1 && product.line_price > 0">
											¥{{ product.line_price }}
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</template>
		</view>
	</view>
</template>

<script>
	export default {
		components: {},
		data() {
			return {
				placeholderImg: '../../static/images/placeholder.png',
				scrollTop: 0,
				windowHeight: 0,
				windowWidth: 0,
				loadedImages: new Set(), // 记录已加载的图片索引
				scrollTimer: null, // 滚动节流计时器
				checkTimer: null // 定时检查器
			};
		},
		props: ['itemData'],
		created() {
			// 初始化商品数据，添加图片显示控制标记
			if (this.itemData && this.itemData.data) {
				this.itemData.data = this.itemData.data.map(item => ({
					...item,
					showImage: false
				}));
			}
		},
		mounted() {
			// 获取窗口尺寸
			try {
				const sysInfo = uni.getSystemInfoSync();
				this.windowHeight = sysInfo.windowHeight || 667; // 默认值兼容
				this.windowWidth = sysInfo.windowWidth || 375; // 默认值兼容
			} catch (e) {
				// 无法获取系统信息时使用默认值
				this.windowHeight = 667;
				this.windowWidth = 375;
			}

			// 初始检查可见图片
			this.checkVisibleImages();

			// 启动定时检查（作为滚动监听的补充，确保所有场景都能触发）
			this.checkTimer = setInterval(() => {
				this.checkVisibleImages();
			}, 1000); // 每1秒检查一次
		},
		beforeDestroy() {
			// 清理计时器
			if (this.scrollTimer) clearTimeout(this.scrollTimer);
			if (this.checkTimer) clearInterval(this.checkTimer);
			this.loadedImages.clear();
		},
		methods: {
			// 处理纵向滚动（节流处理）
			handleVerticalScroll() {
				this.handleScroll();
			},

			// 处理横向滚动（节流处理）
			handleHorizontalScroll() {
				this.handleScroll();
			},

			// 统一的滚动处理函数
			handleScroll() {
				if (this.scrollTimer) {
					clearTimeout(this.scrollTimer);
				}
				// 50ms节流
				this.scrollTimer = setTimeout(() => {
					this.checkVisibleImages();
				}, 50);
			},

			// 检查所有图片是否在可视区域
			checkVisibleImages() {
				if (!this.itemData || !this.itemData.data) return;

				// 只检查未加载的图片
				this.itemData.data.forEach((product, index) => {
					if (!this.loadedImages.has(index)) {
						this.checkImageVisible(index);
					}
				});
			},

			// 检查单个图片是否可见
			checkImageVisible(index) {
				const query = uni.createSelectorQuery().in(this);
				query.select(`.product-img[data-index="${index}"]`).boundingClientRect(data => {
					if (data && this.isVisible(data)) {
						// 图片进入可视区域，加载图片
						this.$set(this.itemData.data[index], 'showImage', true);
						this.loadedImages.add(index);
					}
				}).exec();
			},

			// 判断元素是否可见
			isVisible(rect) {
				// 元素与视口有重叠即视为可见
				return (
					rect.top < this.windowHeight &&
					rect.bottom > 0 &&
					rect.left < this.windowWidth &&
					rect.right > 0
				);
			},

			// 跳转产品详情
			gotoDetail(productId) {
				const url = `/pages/product/detail/detail?product_id=${productId}`;
				this.gotoPage(url); // 假设gotoPage是全局路由方法
			}
		}
	};
</script>

<style>
	/* 新增纵向滚动容器样式 */
	.vertical-scroll {
		height: 100%;
		width: 100%;
	}

	.diy-product {
		padding: 0 20rpx;
		height: 100%;
	}

	/* 图片样式优化 */
	.product-img {
		transition: opacity 0.3s ease-in-out;
	}

	.product-img[src*="placeholder"] {
		background: #f5f5f5;
	}

	/* 列表布局样式 */
	.product-list.column__1 .product-item {
		margin-bottom: 20rpx;
		background: #ffffff;
		width: 100%;
	}

	.product-list.column__1 .product-item-box {
		display: flex;
		justify-content: flex-start;
		align-items: stretch;
	}

	.product-list .product-cover {
		overflow: hidden;
		position: relative;
	}

	.product-list .product-cover image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.product-list.column__1 .product-cover {
		width: 240rpx;
		height: 240rpx;
		border-radius: 20rpx;
	}

	.product-list.column__1 .product-info {
		margin: 20rpx 20rpx 20rpx 30rpx;
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.product-list .product-info .already-sale text {
		padding: 4rpx 8rpx;
		border-radius: 8rpx;
		background: #f2f2f7;
		color: #999;
	}

	.product-list .product-title {
		display: -webkit-box;
		font-size: 32rpx;
		overflow: hidden;
		word-wrap: break-word;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}

	.product-list.column__1 .product-title {
		max-height: 80rpx;
		line-height: 40rpx;
	}

	.product-list.column__1 .selling-point {
		display: -webkit-box;
		overflow: hidden;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		line-height: 30rpx;
		max-height: 60rpx;
	}

	.product-list.column__1 .already-sale {
		margin-top: 10rpx;
	}

	.product-list.column__2 .product-title {
		height: 80rpx;
		line-height: 40rpx;
		margin-top: 20rpx;
		font-size: 26rpx;
		margin-bottom: 20rpx;
	}

	.product-list.column__3 .product-title {
		margin-top: 20rpx;
		margin-left: 10rpx;
		margin-right: 10rpx;
		height: 72rpx;
		line-height: 36rpx;
		font-size: 30rpx;
	}

	.product-list.column__2 .product-info {
		padding: 0 24rpx;
	}

	.product-list .price {
		font-size: 34rpx;
	}

	.product-list.column__2 .price {
		margin-top: 10rpx;
		font-size: 30rpx;
	}

	.product-list.column__3 .price {
		margin-top: 10rpx;
		padding: 0 10rpx;
		font-size: 28rpx;
	}

	.product-list.column__3 .price .text-d-line {
		font-size: 22rpx;
	}

	.product-list.column__2,
	.product-list.column__3 {
		display: flex;
		flex-wrap: wrap;
		justify-content: flex-start;
	}

	.column__2 .product-item {
		width: 345rpx;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
		padding-bottom: 20rpx;
		overflow: hidden;
		background: #ffffff;
		box-shadow: 0px 8rpx 3rpx 0px rgba(6, 0, 1, 0.03);
		border-radius: 12rpx;
	}

	.display__list .column__2 .product-item:nth-child(2n) {
		margin-right: 0;
	}

	.column__2 .product-cover {
		width: 100%;
		height: 220rpx;
		border-radius: 12rpx;
		margin: 0 auto;
	}

	.column__3 .product-item {
		width: 230rpx;
		margin-bottom: 10rpx;
		margin-right: 10rpx;
		padding-bottom: 10rpx;
		border-radius: 8rpx;
		overflow: hidden;
		background: #ffffff;
		box-shadow: 0 0 8rpx rgba(0, 0, 0, 0.1);
	}

	.display__list .column__3 .product-item:nth-child(3n) {
		margin-right: 0;
	}

	.column__3 .product-cover {
		width: 230rpx;
		height: 230rpx;
	}

	.display__slide .product-list {
		flex-wrap: nowrap;
	}

	.display__slide .column__2 .product-item {
		width: 300rpx;
	}

	.display__slide .column__3 .product-item {
		width: 200rpx;
	}

	.horizontal-scroll {
		white-space: nowrap;
		padding-bottom: 20rpx;
	}
</style>